<template>
  <div class="smart-plan-detail-container" v-loading="loading">
    <no-auth v-if="!loading && !hasViewAuth"></no-auth>
    <!-- start 顶部操作区 -->
    <div class="smart-plan-detail-header mar-b-12" v-if="hasViewAuth">
      <div class="smart-plan-detail-header__left">
        {{ formValue.planName }} <span class="delete-status mar-l-5" v-if="isDeleted">{{ $t('common.base.deleted') }}</span>
      </div>
      <div class="smart-plan-detail-header__right">
        <template v-if="allowEditSmartPlan">
          <el-button type="primary" @click="editPlan" v-if="allowEditSmartPlan">{{ $t('task.taskTypes.planTask.editTask') }}</el-button>
          <el-dropdown class="mar-l-12" @command="handleHeaderCommand" v-if="showMoreButton">
            <el-button type="info" plain>
              {{ $t('common.base.more') }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="editName" v-if="allowEditSmartPlan">{{ $t('smartPlan.editName') }}</el-dropdown-item>
              <el-dropdown-item command="copy" v-if="allowCopySmartPlan">{{ $t('common.base.copy') }}</el-dropdown-item>
              <el-dropdown-item command="cancelTask" v-if="allowEditSmartPlan">{{ $t('task.taskTypes.planTask.cancelTask') }}</el-dropdown-item>
              <el-dropdown-item command="delete" v-if="allowDeleteSmartPlan">{{ $t('common.base.delete') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template v-else>
          <el-button type="primary" @click="copyPlan" v-if="allowCopySmartPlan">{{ $t('common.base.copy') }}</el-button>
          <el-button type="danger" @click="deletePlan" v-if="allowDeleteSmartPlan">{{ $t('common.base.delete') }}</el-button>
        </template>
      </div>
    </div>
    <!-- end 顶部操作区 -->
    <!-- start 计划详情折叠面板 -->
    <div class="smart-plan-detail-main" v-if="hasViewAuth">
      <base-collapse class="smart-plan-detail-main-content" :direction.sync="collapseDirection">
        <template slot="left">
          <div class="smart-plan-detail-main-content__left" v-show="collapseDirection != 'left'">
            <el-tabs v-model="leftActiveTab" v-if="isInit">
              <el-tab-pane :label="$t('common.base.basicInfo')" name="smart-plan-view">
                <smart-plan-view :fields="fields" :form-value="formValue"></smart-plan-view>
              </el-tab-pane>
              <el-tab-pane :label="$t('smartPlan.planRange')" name="smart-plan-range">
                <smart-plan-range
                  :plan-id="planId"
                  :create-dimension="formValue.createDimension"
                  @updateDynamicInfo="updateDynamicInfo"
                  :allow-edit-smart-plan="allowEditSmartPlan"
                ></smart-plan-range>
              </el-tab-pane>
              <el-tab-pane :label="$t('smartPlan.taskDetails')" name="smart-plan-details">
                <smart-plan-details
                  :plan-id="planId"
                  :biz-type="formValue.planType"
                  :plan-type-id="formValue.planTypeId"
                  :period-setting="formValue.periodSetting"
                  :end-setting="formValue.endSetting"
                  :allow-edit-smart-plan="allowEditSmartPlan"
                  @updateDynamicInfo="updateDynamicInfo"
                ></smart-plan-details>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="collapse-left" v-show="collapseDirection == 'left'">{{ leftActiveLabel }}</div>
        </template>
        <template slot="right">
          <div class="smart-plan-detail-main-content__right" v-show="collapseDirection != 'right'">
            <el-tabs v-model="rightActiveTab">
              <el-tab-pane :label="$t('common.base.dynamicInfo')" name="smart-plan-dynamic-info">
                <smart-plan-dynamic-info ref="smartPlanDynamicInfo" :plan-id="planId" :plan-type-name="formValue.planTypeName"></smart-plan-dynamic-info>
              </el-tab-pane>
              <el-tab-pane :label="$t('smartPlan.operation')" name="smart-plan-operation">
                <smart-plan-operation v-if="rightActiveTab == 'smart-plan-operation'" :plan-id="planId"></smart-plan-operation>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="collapse-left" v-show="collapseDirection == 'right'">{{ rightActiveLabel }}</div>
        </template>
      </base-collapse>
    </div>
    <!-- end 计划详情折叠面板 -->
    <edit-plan-name-dialog ref="editPlanNameDialog" :plan-id="planId" @editPlanNameSuccess="editPlanNameSuccess"></edit-plan-name-dialog>
    <copy-plan-name-dialog ref="copyPlanNameDialog" :plan-id="planId" :form-value="formValue"></copy-plan-name-dialog>
  </div>
</template>

<script>
/* components */
import noAuth from '@src/component/auth/noAuth'
import SmartPlanView from './components/smartPlanView'
import SmartPlanRange from './components/smartPlanRange'
import SmartPlanDetails from './components/smartPlanDetails'
import SmartPlanDynamicInfo from './components/smartPlanDynamicInfo'
import SmartPlanOperation from './components/smartPlanOperation'
import EditPlanNameDialog from './components/editPlanNameDialog'
import CopyPlanNameDialog from './components/copyPlanNameDialog'
/* api */
import * as SmartPlanApi from '@src/modules/smartPlan/api/index.js'
/* mixin */
import SmartPlanMixin from '@src/modules/smartPlan/mixin/index.js'
/* util */
import { getFixedColumns } from './fields'
import { packToForm } from '../util/index'
import { t } from '@src/locales'
import qs from 'qs'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { openAccurateTab } from '@src/util/platform'

export default {
  name: 'smart-plan-detail',
  mixins: [SmartPlanMixin],
  data() {
    return {
      loading: false,
      isInit: false,
      planId: '',
      formValue: {},
      fields: [],
      collapseDirection: '',
      leftActiveTab: 'smart-plan-view',
      rightActiveTab: 'smart-plan-dynamic-info',
    }
  },
  computed: {
    leftActiveLabel() {
      if (this.leftActiveTab == 'smart-plan-view') return t('common.base.basicInfo')
      if (this.leftActiveTab == 'smart-plan-range') return t('smartPlan.planRange')
      if (this.leftActiveTab == 'smart-plan-details') return t('smartPlan.taskDetails')
      return ''
    },
    rightActiveLabel() {
      if (this.rightActiveTab == 'smart-plan-dynamic-info') return t('common.base.dynamicInfo')
      if (this.rightActiveTab == 'smart-plan-operation') return t('smartPlan.operation')
      return ''
    },
    /* 是否在进行中状态 */
    isProcessing() {
      return this.formValue.planStatus == 0
    },
    /* 是否已删除 */
    isDeleted() {
      return this.formValue.deleted == 1
    },
    /* 允许编辑智能计划 */
    allowEditSmartPlan() {
      return this.hasEditAuth && this.isProcessing && !this.isDeleted
    },
    /* 允许复制智能计划 */
    allowCopySmartPlan() {
      return this.hasCreateAuth && !this.isDeleted
    },
    /* 允许删除智能计划 */
    allowDeleteSmartPlan() {
      return this.hasDeleteAuth && !this.isDeleted
    },
    showMoreButton() {
      return this.allowEditSmartPlan || this.allowCopySmartPlan || this.allowDeleteSmartPlan
    },
  },
  created() {
    let query = qs.parse(window.location.search.substr(1)) || {};
    this.planId = query.planId
    let collapseDirection = sessionStorage.getItem(`smart_plan_collapseDirection_${this.planId}`);
    this.collapseDirection = collapseDirection || '';
    this.fields = getFixedColumns()
  },
  mounted() {
    this.initialize()
  },
  methods: {
    initialize() {
      const currentTabId = window.frameElement?.dataset?.id;
      this.$platform.setTabTitle({
        id: currentTabId,
        title: t('common.pageTitle.otherPageTitle.jobNotificationItem.title5')
      })
      this.loading = true
      SmartPlanApi.getDetail({ id: this.planId }).then(res => {
        this.loading = false
        this.isInit = true
        this.formValue = packToForm(res.data || {})
        // 当任务类型为工单事件时显示派单设置
        if (!['TASK', 'EVENT'].includes(this.formValue.planType)) {
          this.fields = this.fields.filter(f => f.fieldName != 'allotSetting')
        }
      })
    },
    editPlan() {
      // 缓存数据，跳转编辑智能计划页面
      localStorage.setItem('createSmartPlanData', JSON.stringify({
        planName: this.formValue.planName,
        planType: this.formValue.planType,
        planTypeId: this.formValue.planTypeId,
        planTypeName: this.formValue.planTypeName,
      }))
      let fromId = window.frameElement?.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSmartPlanEdit,
        params: `planId=${this.planId}`,
        fromId
      })
    },
    copyPlan() {
      this.$refs.copyPlanNameDialog.open(`${this.formValue.planName}_copy`)
    },
    async deletePlan() {
      let confirm = await this.$platform.confirm(t('smartPlan.deleteTip'));
      if (confirm) {
        SmartPlanApi.deletePlan({id: this.planId}).then(res => {
          let isSucc = res.success || res.succ;
        
          this.$platform.notification({
            type: isSucc ? 'success' : 'error',
            title: isSucc ? t('common.base.tip.operationSuccess') : t('common.base.tip.operationFail'),
            message: !isSucc && res.message
          })
          // 删除成功后关闭当前页面并刷新from页面
          if (isSucc) {
            this.closeAndRefreshFromTab()
          }
        })
      }
    },
    async handleHeaderCommand(command) {
      if (command == 'editName') {
        this.$refs.editPlanNameDialog.open(this.formValue.planName)
      } else if (command == 'copy') {
        this.copyPlan()
      } else if (command == 'cancelTask') {
        let confirm = await this.$platform.confirm(t('smartPlan.cancelTip'));
        if (confirm) {
          SmartPlanApi.cancelPlan({id: this.planId}).then(res => {
            let isSucc = res.success || res.succ;
          
            this.$platform.notification({
              type: isSucc ? 'success' : 'error',
              title: isSucc ? t('common.base.tip.operationSuccess') : t('common.base.tip.operationFail'),
              message: !isSucc && res.message
            })
            // 取消成功后刷新当前页面
            if (isSucc) {
              setTimeout(() => {
                this.refreshFromTab()
                window.location.reload()
              }, 300)
            }
          })
        }
      } else if (command == 'delete') {
        this.deletePlan()
      }
    },
    // 编辑计划名称成功
    editPlanNameSuccess(name) {
      this.formValue.planName = name
      this.refreshFromTab()
    },
    // 更新动态信息
    updateDynamicInfo() {
      this.$refs.smartPlanDynamicInfo.searchRecord()
    },
  },
  components: {
    noAuth,
    SmartPlanView,
    SmartPlanRange,
    SmartPlanDetails,
    SmartPlanDynamicInfo,
    SmartPlanOperation,
    EditPlanNameDialog,
    CopyPlanNameDialog,
  },
}
</script>

<style lang="scss" scoped>
.smart-plan-detail-container {
  padding: 12px;
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
  overflow: hidden;
  .smart-plan-detail-header {
    height: 56px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    padding: 0 16px;
    border-radius: 5px;
    &__left {
      font-size: 16px;
      font-weight: bold;
      .delete-status {
        color: #F56C6C;
        font-size: $font-size-small;
        font-weight: normal;
      }
    }
    &__right {
      display: flex;
    }
    .el-button--info.is-plain {
      background: #F5F8FA;
      color: #595959;
      font-weight: normal;
      .el-icon--right {
        color: #262626;
      }
    }
  }
  .smart-plan-detail-main {
    flex: 1;
    overflow: auto;
  }
  .base-collapse {
    min-height: 100%;
    overflow: auto;
    ::v-deep .resize-bar {
      height: 100vh;
    }
  }
  .collapse-left,
  .collapse-right {
    height: 40px;
    line-height: 40px;
    padding-left: 12px;
    color: $text-color-regular;
    border-bottom: 2px solid $color-border-l2;
  }
  ::v-deep .base-collapse-left, ::v-deep .base-collapse-right {
    height: auto;
  }
  ::v-deep .el-tabs__nav-wrap {
    background: #F7F8F8;
  }
  ::v-deep .el-tabs__item {
    padding: 0 20px !important;
  }
}
</style>